package com.ruoyi.system.webSocket;//package com.ruoyi.system.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/chat/{driverId}/{id}")
@Component
@Slf4j
public class ChatEndPoint {

    private Session session;
    //司机集合
    private static CopyOnWriteArraySet<ChatEndPoint> webSocket = new CopyOnWriteArraySet<>();


    /**
     * 建立连接 todo 司机上线 [ws://127.0.0.1:9207/api/pushMessage/1]
     * @param session
     * @param driverId
     */
    @OnOpen
    public void OnOpen(Session session,@PathParam("driverId") String driverId){
        this.session = session;
        //司机添加进集合
        webSocket.add(this);
        //司机在线人数
        log.info("司机在线人数共有"+webSocket.size()+"人");

    }

    /**
     * 断开连接 todo 司机下线
     * @param session
     */
    @OnClose
    public void OnClose(Session session) {
        webSocket.remove(this);
        //退出连接
        log.info("剩余接单司机"+webSocket.size()+"人");

    }


    /**
     * 监听客户端发送的消息 todo 司机抢单
     * @param message
     */
    @OnMessage
    public void OnMessage(String message, @PathParam("driverId") String driverId,@PathParam("id") String id) {
        //用户取消
        System.out.println(message);
        log.info("司机ID"+driverId+"订单ID"+id);

    }

    /**
     * 发送消息 todo 发送订单信息给司机
     * @param message
     */

    public void sendMessage(String message) {
        log.info("发送订单信息给司机:"+message);

        //发送新的订单信息给前端
        for (ChatEndPoint webSocketController : webSocket) {
            log.info("message",message);
            try{
                webSocketController.session.getBasicRemote().sendText(message);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 异常处理 todo 异常处理
     * @param throwable
     * @param session
     */
    @OnError
    public void OnError(Throwable throwable,Session session) {
        //异常
        System.out.println("OnError");
    }

}
